package priv.mill.main;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;

import priv.mill.servlet.ErfenServlet;
import priv.mill.servlet.SortServlet;

public class Main {
	public static class EncodingFilter implements Filter{

		public void destroy() {
			
		}

		public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
				throws IOException, ServletException {
			HttpServletRequest request=(HttpServletRequest) arg0;
			
			request.setCharacterEncoding("utf-8");
			HttpServletResponse response=(HttpServletResponse) arg1;
			response.setContentType("application/json;charset=utf-8");
			arg2.doFilter(arg0, arg1);
		}

		public void init(FilterConfig arg0) throws ServletException {
			
		}

	}

	public static void main(String[] args) throws Exception {

		Server server = new Server();
		ServerConnector connector = new ServerConnector(server);
		connector.setPort(9999);
		Connector[] connectors = {connector};
		server.setConnectors(connectors);
		ContextHandlerCollection handler =new  ContextHandlerCollection();
		ServletContextHandler context = new ServletContextHandler();
		context.setContextPath("/");
		//添加servlet
		context.addServlet(ErfenServlet.class, "/erfen");
		context.addServlet(SortServlet.class, "/sort");
		//添加filter
		context.addFilter(EncodingFilter.class, "/*", null);
		Handler[] handlers = {context,new DefaultHandler()};
		handler.setHandlers(handlers);
		server.setHandler(handler);
		
		server.start();
		server.join();
	}
}
